        <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Arrays" %>
<%@ page import="java.util.stream.Collectors" %>
<%@ page import="slh.movie.Movie" %>
<%@ page import="slh.comment.comment" %>
<%@ page import="slh.commentVote.commentVoteDao" %>
<%@ page import="java.util.Base64" %>
<%@ page import="wty.Bee.UserDao" %>
<%@ page import="wty.Bee.User" %>

<style>
    /* 豆瓣详情页基础样式 */
    * {
        font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
        color: #333;
        box-sizing: border-box;
    }

    body {
        background-color: #f5f5f5;
        margin: 0;
        padding: 20px;
    }

    .detail-container {
        max-width: 1200px;
        margin: 0 auto;
        background-color: white;
        border-radius: 12px;
        box-shadow: 0 2px 15px rgba(0,0,0,0.05);
        padding: 30px 40px;
    }

    /* 头部信息区 */
    .header-section {
        display: flex;
        gap: 30px;
        margin-bottom: 30px;
    }

    .cover-image {
        width: 220px;
        height: 300px;
        object-fit: cover;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

    .basic-info {
        flex: 1;
    }

    .movie-title {
        font-size: 28px;
        font-weight: 600;
        color: #2f2f2f;
        margin-bottom: 10px;
    }

    .meta-info {
        color: #666;
        font-size: 14px;
        margin-bottom: 20px;
    }

    .meta-info span.divider {
        margin: 0 5px;
    }

    .rating-block {
        display: flex;
        align-items: center;
        margin: 20px 0;
    }

    .stars {
        font-size: 24px;
        color: #f1b44c;
        margin-right: 10px;
    }

    .score {
        font-size: 28px;
        color: #1b74e4;
        font-weight: 500;
        margin-right: 15px;
    }

    .tag-list {
        margin-top: 15px;
    }

    .tag {
        display: inline-block;
        background-color: #f5f5f5;
        color: #666;
        font-size: 12px;
        padding: 3px 8px;
        border-radius: 15px;
        margin-right: 5px;
    }

    /* 内容区样式 */
    .section-title {
        font-size: 20px;
        font-weight: 500;
        color: #2f2f2f;
        border-left: 4px solid #1b74e4;
        padding-left: 10px;
        margin: 30px 0 20px;
    }

    .description {
        line-height: 1.8;
        color: #555;
    }

    /* 评论区样式 */
    .comment-section {
        margin-top: 40px;
    }

    .comment-list {
        margin-top: 20px;
    }

    .comment-item {
        padding: 20px 0;
        border-bottom: 1px dashed #e0e0e0;
    }

    .comment-header {
        display: flex;
        align-items: center;
        gap: 15px;
        margin-bottom: 10px;
    }

    .user-avatar {
        width: 48px;
        height: 48px;
        border-radius: 50%;
        background-color: #f0f0f0;
        object-fit: cover;
    }

    .user-info {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 14px;
        color: #666;
    }

    .user-name {
        color: #2f2f2f;
        font-weight: 500;
    }

    .comment-rating {
        color: #f1b44c;
    }

    .comment-content {
        line-height: 1.6;
        color: #555;
        margin-left: 63px;
    }

    .comment-time {
        font-size: 12px;
        color: #999;
        margin-top: 8px;
        margin-left: 63px;
    }

    .reply-link {
        color: #1b74e4;
        text-decoration: none;
        margin-left: 15px;
        font-size: 13px;
    }

    /* 评论表单样式 */
    .comment-form {
        background-color: #f9f9f9;
        padding: 20px;
        border-radius: 8px;
        margin-top: 30px;
    }

    .form-title {
        font-size: 18px;
        margin-bottom: 15px;
        color: #333;
    }

    .rating-input {
        margin-bottom: 15px;
    }

    .rating-label {
        margin-right: 10px;
        font-size: 14px;
    }

    .star-rating {
        display: inline-block;
        font-size: 24px;
        cursor: pointer;
    }

    .star-rating span {
        color: #ddd;
        margin-right: 5px;
    }

    .star-rating span.active {
        color: #f1b44c;
    }

    .comment-textarea {
        width: 100%;
        height: 120px;
        padding: 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        resize: vertical;
        font-size: 14px;
        margin-bottom: 15px;
    }

    .submit-btn {
        background-color: #1b74e4;
        color: white;
        border: none;
        padding: 8px 20px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
    }

    .submit-btn:hover {
        background-color: #1557b0;
    }

    /* 评分统计 */
    .rating-stats {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
    }

    .rating-average {
        font-size: 28px;
        color: #1b74e4;
        font-weight: 500;
        margin-right: 20px;
    }

    .rating-distribution {
        flex: 1;
    }

    .rating-bar {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
    }

    .rating-label {
        width: 60px;
        font-size: 13px;
        color: #666;
    }

    .rating-progress {
        flex: 1;
        height: 10px;
        background-color: #eee;
        border-radius: 5px;
        overflow: hidden;
    }

    .rating-fill {
        height: 100%;
        background-color: #f1b44c;
    }

    /* 响应式调整 */
    @media (max-width: 768px) {
        .detail-container {
            padding: 20px;
        }

        .header-section {
            flex-direction: column;
            align-items: center;
            gap: 20px;
        }

        .cover-image {
            width: 180px;
            height: 240px;
        }
    }

    @media (max-width: 480px) {
        .movie-title {
            font-size: 24px;
        }

        .comment-header {
            flex-direction: column;
            align-items: flex-start;
            gap: 8px;
        }

        .comment-content,
        .comment-time {
            margin-left: 0;
        }
    }

    /* 加载动画 */
    .loading {
        display: none;
        text-align: center;
        padding: 20px;
    }

    .spinner {
        border: 4px solid rgba(0, 0, 0, 0.1);
        width: 36px;
        height: 36px;
        border-radius: 50%;
        border-left-color: #1b74e4;
        animation: spin 1s linear infinite;
        margin: 0 auto;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    /* 错误提示 */
    .error-message {
        color: #e74c3c;
        background-color: #fdecea;
        padding: 10px;
        border-radius: 4px;
        margin-bottom: 15px;
        display: none;
    }

    /* 成功提示 */
    .success-message {
        color: #2ecc71;
        background-color: #e8f8f0;
        padding: 10px;
        border-radius: 4px;
        margin-bottom: 15px;
        display: none;
    }
    .favorite-btn {
        background-color: #f5f5f5;
        border: 1px solid #ddd;
        border-radius: 20px;
        padding: 8px 15px;
        font-size: 14px;
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 5px;
        transition: all 0.3s;
    }

    .favorite-btn:hover {
        background-color: #f0f0f0;
    }

    .favorite-btn.active {
        background-color: #ffebee;
        border-color: #e57373;
    }

    .favorite-btn.active #favoriteIcon {
        color: #e53935;
    }
    /* 投票按钮样式 */
    .comment-actions {
        margin-left: 63px;
        margin-top: 10px;
        display: flex;
        gap: 10px;
    }

    .vote-btn {
        background: none;
        border: 1px solid #ddd;
        border-radius: 15px;
        padding: 3px 10px;
        font-size: 12px;
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 5px;
        transition: all 0.2s;
    }

    .vote-btn:hover {
        background-color: #f5f5f5;
    }

    .vote-btn.active {
        border-color: #1b74e4;
        background-color: #e7f0fa;
    }

    .vote-btn.upvote.active {
        border-color: #2ecc71;
        background-color: #e8f8f0;
    }

    .vote-btn.downvote.active {
        border-color: #e74c3c;
        background-color: #fdecea;
    }

    .vote-btn .icon {
        font-size: 14px;
    }

    .vote-btn .count {
        color: #666;
    }

    .vote-btn.active .count {
        color: #333;
        font-weight: 500;
    }
    .comment-sorting {
        margin: 20px 0 10px;
        display: flex;
        gap: 10px;
    }

    .sort-btn {
        padding: 6px 15px;
        background-color: #f5f5f5;
        border: 1px solid #ddd;
        border-radius: 15px;
        font-size: 14px;
        cursor: pointer;
        transition: all 0.2s;
    }

    .sort-btn:hover {
        background-color: #eee;
    }

    .sort-btn.active {
        background-color: #1b74e4;
        color: white;
        border-color: #1b74e4;
    }
</style>
<%
    String userId = (String) request.getAttribute("userId");
    Movie movie = (Movie) request.getAttribute("movie");
    List<comment> comments = (List<comment>) request.getAttribute("comments");
    Double averageRating = (Double) request.getAttribute("avgRating");
    int[] ratingCounts = (int[]) request.getAttribute("ratingCounts");
    int totalComments = comments != null ? comments.size() : 0;
    commentVoteDao commentVoteDao = new commentVoteDao();
    // 默认值处理
    if (movie == null) {
        movie = new Movie();
        movie.setTitle("未知电影");
        movie.setDirector("未知导演");
        movie.setReleaseDate(null);
        movie.setDuration(0);
        movie.setScore(0);
        movie.setGenre("");
        movie.setDescription("暂无描述");
        movie.setCoverImage("images/default-movie.jpg");
    }

    if (comments == null) {
        comments = List.of();
    }

    if (averageRating == null) {
        averageRating = 0.0;
    }

    if (ratingCounts == null) {
        ratingCounts = new int[5];
    }
%>
<div class="detail-container">
    <div class="header-section">
        <img src="<%=movie.getCoverImage()%>" alt="<%=movie.getTitle()%>" class="cover-image">
        <div class="basic-info">
            <h1 class="movie-title"><%=movie.getTitle()%></h1>
            <div class="meta-info">
                <span>导演：<%=movie.getDirector()%></span>
                <span class="divider">/</span>
                <span>主演：<%=movie.getActors() != null ? movie.getActors() : "未知"%></span>
                <span class="divider">/</span>
                <span>上映日期：<%=movie.getReleaseDate() != null ? movie.getReleaseDate() : "未知"%></span>
                <span class="divider">/</span>
                <span>片长：<%=movie.getDuration() > 0 ? movie.getDuration() + "分钟" : "未知"%></span>
            </div>
            <div class="rating-block">
                <div class="stars" id="averageStars">
                    <% int fullStars = (int) Math.round(averageRating); %>
                    <% for (int i = 1; i <= 5; i++) { %>
                    <span style="color:<%=i <= fullStars ? "#f1b44c" : "#ddd"%>">★</span>
                    <% } %>
                </div>
                <span class="score" id="averageScore"><%=String.format("%.1f", averageRating * 2)%></span>
                <span class="tag-list">
                    <% if (movie.getGenre() != null && !movie.getGenre().isEmpty()) { %>
                <%=Arrays.stream(movie.getGenre().split(","))
                        .map(g -> "<span class='tag'>" + g + "</span>")
                        .collect(Collectors.joining())%>
                <% } %>
                </span>
            </div>
            <p class="description"><%=movie.getDescription()%></p>
        </div>
    </div>
    <div class="favorite-section" style="margin: 15px 0;">

        <button id="favoriteBtn" class="favorite-btn"
                data-movie-id="<%=movie.getMovieId()%>">
            <span id="favoriteIcon">❤</span>
            <span id="favoriteText">收藏</span>
        </button>
    </div>

    <div class="comment-section">
        <h2 class="section-title">用户评论（<span id="totalComments"><%=totalComments%></span>条）</h2>



        <!-- 加载动画 -->
        <div class="loading" id="loadingIndicator">
            <div class="spinner"></div>
            <p>正在提交评论...</p>
        </div>

        <!-- 评分统计 -->
        <div class="rating-stats">
            <div class="rating-average">
                <span id="averageRatingText"><%=String.format("%.1f", averageRating * 2)%></span> <span style="font-size:14px;color:#666;">/ 10分</span>
            </div>
            <div class="rating-distribution" id="ratingDistribution">
                <% for (int i = 5; i >= 1; i--) { %>
                <div class="rating-bar" data-rating="<%=i%>">
                    <span class="rating-label"><%=i%>星</span>
                    <div class="rating-progress">
                        <div class="rating-fill" style="width:
                            <%=totalComments > 0 ? (ratingCounts[i - 1] * 100 / totalComments) : 0%>%"></div>
                    </div>
                    <span style="font-size:12px;color:#999;margin-left:10px;width:30px;text-align:right;">
                        <%=totalComments > 0 ? (ratingCounts[i - 1] * 100 / totalComments) : 0%>%
                    </span>
                </div>
                <% } %>
            </div>
        </div>
        <!-- 消息提示区域 -->
        <div class="error-message" id="errorMessage"></div>
        <div class="success-message" id="successMessage"></div>
        <!-- 评论表单 -->
        <div class="comment-form">
            <h3 class="form-title">发表评论</h3>
            <form id="commentForm">
                <input type="hidden" name="movieId" value="<%=movie.getMovieId()%>">
                <div class="rating-input">
                    <span class="rating-label">评分：</span>
                    <div class="star-rating" id="starRating">
                        <span data-value="1">★</span>
                        <span data-value="2">★</span>
                        <span data-value="3">★</span>
                        <span data-value="4">★</span>
                        <span data-value="5">★</span>
                    </div>
                    <input type="hidden" name="rating" id="ratingValue" value="0">
                </div>
                <textarea class="comment-textarea" name="comment" id="commentText" placeholder="写下你的观后感..." required></textarea>
                <button type="submit" class="submit-btn" id="submitBtn">提交评论</button>
            </form>
        </div>
        <!-- 评论排序选项 -->
        <div class="comment-sorting">
            <button class="sort-btn active" data-sort="latest">最新</button>
            <button class="sort-btn" data-sort="hottest">最热</button>
        </div>
        <!-- 评论列表 -->
        <div class="comment-list" id="commentListContainer">
    <% for (comment comment : comments) {
        int rating = comment.getRating() != 0 ? comment.getRating() : 0;
        rating = Math.max(1, Math.min(rating, 5));
        User commentUser = new UserDao().selectById(comment.getUserId());
    %>
    <div class="comment-item">
        <div class="comment-header">
            <img src="" id="userAvatar_<%=comment.getCommentId()%>" alt="用户头像" class="user-avatar">
            <script>
                // 使用立即执行函数确保作用域隔离
                (function() {
                    const avatarImg = document.getElementById('userAvatar_<%=comment.getCommentId()%>');
                    const user = <%=commentUser != null && commentUser.getAvatar() != null ?
                    "{'avatar': '" + Base64.getEncoder().encodeToString(commentUser.getAvatar()) + "'}" :
                    "null"%>;
                    if (user && user.avatar) {
                        avatarImg.src = 'data:image/png;base64,' + user.avatar;
                    } else {
                        avatarImg.src = "https://img.shetu66.com/2023/04/25/1682410853619598.png";
                    }
                })();
            </script>
                    <div class="user-info">
                        <span class="user-name"><%=commentUser.getUsername() != null ? commentUser.getUsername() : "匿名用户"%></span>
                        <span class="comment-rating">
                            <% for (int i = 1; i <= 5; i++) { %>
                                <span style="color:<%=i <= rating ? "#f1b44c" : "#ddd"%>">★</span>
                            <% } %>
                        </span>
                    </div>
                </div>
                <p class="comment-content">
                    <%=comment.getCommentText() != null ? comment.getCommentText() : "此用户没有留下评论内容"%></p>
                <div class="comment-actions">

                    <button class="vote-btn upvote
                    <%=commentVoteDao.getUserVote(comment.getCommentId(), userId) != null && commentVoteDao.getUserVote(comment.getCommentId(), userId) == 1 ? "active" : ""%>"
                            data-comment-id="<%=comment.getCommentId()%>">
                        <span class="icon">👍</span>
                        <span class="count"><%=commentVoteDao.getVoteCounts(comment.getCommentId())[0]%></span>
                    </button>
                    <button class="vote-btn downvote
                    <%=commentVoteDao.getUserVote(comment.getCommentId(), userId) != null && commentVoteDao.getUserVote(comment.getCommentId(), userId) == -1 ? "active" : ""%>"
                            data-comment-id="<%=comment.getCommentId()%>">
                        <span class="icon">👎</span>
                        <span class="count"><%=commentVoteDao.getVoteCounts(comment.getCommentId())[1]%></span>
                    </button>
                </div>
                <div class="comment-time">
                    <%=comment.getCreatedAt() != null ? comment.getCreatedAt() : ""%>

                </div>
            </div>
            <% } %>
        </div>
    </div>
</div>

<script>


    // 星级评分交互
    const starRating = document.getElementById('starRating');
    if (starRating) {
        starRating.addEventListener('click', function(e) {
            if (e.target.tagName === 'SPAN') {
                const rating = parseInt(e.target.getAttribute('data-value'));
                const stars = starRating.querySelectorAll('span');

                stars.forEach((star, index) => {
                    star.classList.toggle('active', index < rating);
                });

                document.getElementById('ratingValue').value = rating;
            }
        });

        // 鼠标悬停效果
        starRating.addEventListener('mouseover', function(e) {
            if (e.target.tagName === 'SPAN') {
                const hoverRating = parseInt(e.target.getAttribute('data-value'));
                const stars = starRating.querySelectorAll('span');

                stars.forEach((star, index) => {
                    star.style.color = index < hoverRating ? '#f1b44c' : '#ddd';
                });
            }
        });

        // 鼠标离开恢复选中状态
        starRating.addEventListener('mouseleave', function() {
            const currentRating = parseInt(document.getElementById('ratingValue').value);
            const stars = starRating.querySelectorAll('span');

            stars.forEach((star, index) => {
                star.style.color = index < currentRating ? '#f1b44c' : '#ddd';
            });
        });
    }

    document.getElementById('commentForm').addEventListener('submit', function(e) {
        e.preventDefault();

        const form = e.target;
        const rating = document.getElementById('ratingValue').value;
        const commentText = document.getElementById('commentText').value;
        const movieId = form.movieId.value;
        const submitBtn = document.getElementById('submitBtn');

        // 验证评分
        if (rating <= 0) {
            showMessage('请选择评分', true);
            return;
        }

        // 验证评论内容
        if (!commentText.trim()) {
            showMessage('请输入评论内容', true);
            return;
        }

        // 显示加载指示器
        document.getElementById('loadingIndicator').style.display = 'block';
        submitBtn.disabled = true;

        // 修改这里：使用URLSearchParams构造表单数据
        const formData = new URLSearchParams();
        formData.append('action', 'addComment');
        formData.append('contentId', movieId);
        formData.append('contentType', 'movie');
        formData.append('rating', rating);
        formData.append('comment', commentText);

        // 发送AJAX请求
        fetch('comment', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded', // 添加正确的Content-Type
            },
            body: formData
        })
            .then(async response => {
                // 先获取响应文本
                const text = await response.text();

                // 尝试解析为JSON
                let data;
                try {
                    data = text ? JSON.parse(text) : {};
                } catch (e) {
                    // 如果不是JSON，创建错误对象
                    return {
                        error: text || '服务器返回了非JSON格式的响应',
                        status: response.status
                    };
                }

                // 检查HTTP状态码
                if (!response.ok) {
                    return {
                        error: data.error || `HTTP错误: ${response.status}`,
                        status: response.status
                    };
                }

                return data;
            })
            .then(data => {
                document.getElementById('loadingIndicator').style.display = 'none';
                submitBtn.disabled = false;

                if (data.error) {
                    showMessage(data.error, true);
                    if (data.redirect) {
                        setTimeout(() => window.location.href = data.redirect, 1500);
                    }
                } else if (data.success) {
                    showMessage(data.message || '评论成功!', false);
                    // 清空表单
                    form.reset();
                    // 重置星级评分
                    document.querySelectorAll('#starRating span').forEach(star => {
                        star.classList.remove('active');
                        star.style.color = '#ddd';
                    });
                    document.getElementById('ratingValue').value = '0';
                    // 刷新评论列表
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showMessage('服务器返回了未知响应格式: ' + JSON.stringify(data), true);
                }
            })
            .catch(error => {
                document.getElementById('loadingIndicator').style.display = 'none';
                submitBtn.disabled = false;
                showMessage('提交评论失败: ' + error.message, true);
                console.error('提交评论出错:', error);
            });
    });

    document.addEventListener('DOMContentLoaded', function() {
        const favoriteBtn = document.getElementById('favoriteBtn');
        const movieId = favoriteBtn.getAttribute('data-movie-id');

        // 检查初始收藏状态
        checkFavoriteStatus(movieId);

        // 处理收藏按钮点击
        favoriteBtn.addEventListener('click', function() {
            toggleFavorite(movieId);
        });
    });

    // 检查收藏状态
    function checkFavoriteStatus(movieId) {
        fetch('favorite?action=check&contentId=' + movieId + '&contentType=movie')
            .then(response => response.json())
            .then(data => {
                const favoriteBtn = document.getElementById('favoriteBtn');
                if (data.isFavorite) {
                    favoriteBtn.classList.add('active');
                    document.getElementById('favoriteText').textContent = '已收藏';
                } else {
                    favoriteBtn.classList.remove('active');
                    document.getElementById('favoriteText').textContent = '收藏';
                }
            })
            .catch(error => console.error('检查收藏状态出错:', error));
    }

    // 切换收藏状态
    function toggleFavorite(movieId) {
        const favoriteBtn = document.getElementById('favoriteBtn');
        const isFavorite = favoriteBtn.classList.contains('active');
        const action = isFavorite ? 'remove' : 'add';

        fetch('favorite', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'action=' + action + '&contentId=' + movieId + '&contentType=movie'
        })
            .then(response => {
                // 首先检查 HTTP 状态码
                if (!response.ok) {
                    throw new Error('网络响应异常: ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                if (data.error) {
                    showMessage(data.error, true);
                    if (data.redirect) {
                        setTimeout(() => window.location.href = data.redirect, 1500);
                    }
                } else if (data.success) {
                    if (action === 'add') {
                        favoriteBtn.classList.add('active');
                        document.getElementById('favoriteText').textContent = '已收藏';
                        showMessage('收藏成功!', false);
                    } else {
                        favoriteBtn.classList.remove('active');
                        document.getElementById('favoriteText').textContent = '收藏';
                        showMessage('已取消收藏', false);
                    }
                }
            })
            .catch(error => {
                console.error('切换收藏状态出错:', error);
                showMessage('操作失败: ' + error.message, true);
            });
    }

    // 显示消息函数
    function showMessage(message, isError) {
        const messageDiv = document.getElementById(isError ? 'errorMessage' : 'successMessage');
        messageDiv.textContent = message;
        messageDiv.style.display = 'block';

        // 3秒后隐藏消息
        setTimeout(() => {
            messageDiv.style.display = 'none';
        }, 3000);
    }

    // 评论点赞/点踩功能
    document.addEventListener('DOMContentLoaded', function() {
        // 获取所有投票按钮
        const voteButtons = document.querySelectorAll('.vote-btn');

        // 为每个按钮单独绑定事件
        voteButtons.forEach(button => {
            button.addEventListener('click', function(e) {
                e.preventDefault();

                const target = e.currentTarget; // 直接获取被点击的按钮
                const commentId = target.getAttribute('data-comment-id');

                if (!commentId) {
                    console.error('找不到comment-id属性');
                    return;
                }

                const action = target.classList.contains('upvote') ? 'upvote' : 'downvote';
                const isActive = target.classList.contains('active');
                const requestAction = isActive ? 'remove' : action;

                target.disabled = true;

                const formData = new URLSearchParams();
                formData.append('action', requestAction);
                formData.append('commentId', commentId);

                fetch('comment-vote', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: formData
                })
                    .then(handleResponse)
                    .then(data => {
                        if (data.error) {
                            showMessage(data.error, true);
                        } else if (data.success) {
                            updateVoteUI(commentId, data);
                        }
                    })
                    .catch(handleError)
                    .finally(() => {
                        target.disabled = false;
                    });
            });
        });
    });

    function handleResponse(response) {
        if (!response.ok) {
            throw new Error(`HTTP错误: ${response.status}`);
        }
        return response.json();
    }

    function handleError(error) {
        console.error('请求失败:', error);
        showMessage('操作失败: ' + error.message, true);
        return { error: error.message };
    }

    // 更新投票UI
    function updateVoteUI(commentId, data) {
        // 获取页面中所有投票按钮
        const allUpvoteButtons = document.getElementsByClassName('upvote');
        const allDownvoteButtons = document.getElementsByClassName('downvote');

        // 查找匹配commentId的按钮
        let upvoteBtn, downvoteBtn;

        // 遍历点赞按钮
        for (let i = 0; i < allUpvoteButtons.length; i++) {
            if (allUpvoteButtons[i].getAttribute('data-comment-id') === commentId) {
                upvoteBtn = allUpvoteButtons[i];
                break;
            }
        }

        // 遍历点踩按钮
        for (let i = 0; i < allDownvoteButtons.length; i++) {
            if (allDownvoteButtons[i].getAttribute('data-comment-id') === commentId) {
                downvoteBtn = allDownvoteButtons[i];
                break;
            }
        }

        // 更新投票数
        if (upvoteBtn) {
            const counts = upvoteBtn.getElementsByClassName('count');
            if (counts.length > 0) {
                counts[0].textContent = data.upVotes || 0;
            }
        }

        if (downvoteBtn) {
            const counts = downvoteBtn.getElementsByClassName('count');
            if (counts.length > 0) {
                counts[0].textContent = data.downVotes || 0;
            }
        }

        // 更新按钮状态
        if (upvoteBtn) {
            if (data.userVote === 1) {
                upvoteBtn.classList.add('active');
            } else {
                upvoteBtn.classList.remove('active');
            }
        }

        if (downvoteBtn) {
            if (data.userVote === -1) {
                downvoteBtn.classList.add('active');
            } else {
                downvoteBtn.classList.remove('active');
            }
        }
    }

    // 评论排序功能
    document.addEventListener('DOMContentLoaded', function() {
        const sortButtons = document.querySelectorAll('.sort-btn');
        const commentListContainer = document.getElementById('commentListContainer');

        if (sortButtons.length && commentListContainer) {
            sortButtons.forEach(button => {
                button.addEventListener('click', function() {
                    // 更新活动按钮状态
                    sortButtons.forEach(btn => btn.classList.remove('active'));
                    this.classList.add('active');

                    // 获取排序方式
                    const sortBy = this.getAttribute('data-sort');

                    // 获取所有评论项
                    const commentItems = Array.from(commentListContainer.querySelectorAll('.comment-item'));

                    // 排序评论
                    commentItems.sort((a, b) => {
                        if (sortBy === 'latest') {
                            // 按时间排序（假设时间在comment-time的第一个子节点）
                            const timeA = a.querySelector('.comment-time').childNodes[0].textContent.trim();
                            const timeB = b.querySelector('.comment-time').childNodes[0].textContent.trim();
                            return new Date(timeB) - new Date(timeA);
                        } else {
                            // 按热度排序（点赞数 - 点踩数）
                            const upvotesA = parseInt(a.querySelector('.upvote .count').textContent) || 0;
                            const downvotesA = parseInt(a.querySelector('.downvote .count').textContent) || 0;
                            const scoreA = upvotesA - downvotesA;

                            const upvotesB = parseInt(b.querySelector('.upvote .count').textContent) || 0;
                            const downvotesB = parseInt(b.querySelector('.downvote .count').textContent) || 0;
                            const scoreB = upvotesB - downvotesB;

                            return scoreB - scoreA;
                        }
                    });

                    // 重新插入排序后的评论
                    commentItems.forEach(item => commentListContainer.appendChild(item));
                });
            });

            // 默认触发最新排序
            document.querySelector('.sort-btn[data-sort="latest"]').click();
        }
    });
</script>